
import {cacheTools} from 'nc-lightapp-front';
import CommonAction from './common';
import {getQueryCondition} from '../../../../hrpub/common/utils/utils';

export default class TableAction extends CommonAction {
    constructor(comp) {
        super();
        this.comp = comp;
        this.action = comp.action;
    }

    // 选择一行
    selectRow = (...args) => {
        const {props} = this.comp;
        const {dispatch, editTable} = props;

        let selected = editTable.getAllRows('list').length === editTable.getCheckedRows('list').length

        this.update({
            tableSelectAll: selected
        });
    }

    // 请求表格数据
    postMainTableData = async (postData) => {
        const {
            props: {
                dispatch
            }
        } = this.comp;

        try {
            let res = await dispatch({
                type: 'emp/getMainTableData',
                payload: {
                    postData: postData
                }
            });
            return res;
        }
        catch(e) {
            console.error(`postMainTableData: ${e}`);
            return e;
        }

    }

    // 获取主表数据
    getMainTableData = async ({
        conditions, 
        pageInfo, 
        pk_org, 
        orderBeginTime, 
        billState, 
        orderEndTime, 
        oid, 
        time,
        pk_trnstype,
        hasSearched
    } = {}) => {
        const {props} = this.comp;
        const {search, emp, meta, dispatch, editTable} = props;

        // 保证调用方式有两种，传参，如果没有传惨就从store拿
        !conditions && (conditions = getQueryCondition(props, 'search'));
        !pageInfo && (pageInfo = emp.pageInfo);
        !pk_org && (pk_org = emp.orgValue ? emp.orgValue.refpk : '');
        !orderBeginTime && (orderBeginTime = emp.orderBeginTime);
        !billState && (billState = emp.orderStatus);
        !orderEndTime && (orderEndTime = emp.orderEndTime);
        !oid && (oid = meta.getMeta()['search'].oid);
        !time && (time = emp.orderTimeRange);
        !pk_trnstype && (pk_trnstype = emp.leaveType ? emp.leaveType.refpk : '');
        hasSearched === undefined && (hasSearched = emp.hasSearched);

        if(hasSearched === false) {
            // return;
        }

        let postData = {
            queryAreaCode: 'querybill',
            querytype: 'true',
            querycondition: {
                logic: 'and',
                conditions: []
            },
            ...conditions, 
            pageInfo: {
                ...pageInfo,
                pageIndex: pageInfo.pageIndex
            }, 
            pk_org, 
            beginTime: orderBeginTime, 
            billState: billState.join(','), 
            endTime: orderEndTime, 
            oid, 
            billTime: time,
            pk_trnstype
        };

        // 如果是用户自定义时间范围则时间范围字段置空
        postData.time === 'custom' && (postData.time = '');
        
        let res = await this.postMainTableData(postData);

        if(res.success) {
            let allpks = [];
            let tableData = {rows: []};
            
            if(res.data && res.data.list) {
                let pageInfo = this.deepCopy(res.data.list.pageInfo);
                dispatch({
                    type: 'emp/update',
                    payload: {
                        pageInfo: {
                            ...pageInfo,
                            pageIndex: parseInt(pageInfo.pageIndex)
                        },
                        historyTableQueryCondition: this.deepCopy(postData),
                        tableSelectAll: false
                    }
                });
                tableData = res.data.list;
                allpks = res.data.list.rows.map((item) => {
                    return item.values['pk_partmng'].value;
                });
                cacheTools.set('allpks', allpks);
            }
            else {
                dispatch({
                    type: 'emp/update',
                    payload: {
                        pageInfo: {
                            ...pageInfo,
                            total: 0
                        }
                    }
                });
            }

            editTable.setTableData('list', tableData, false);
        }
    }

    // 当用户点击了全部选择按钮
    selectAll = (props, tableId, status) => {
        this.comp.props.dispatch({
            type: 'emp/update',
            payload: {
                tableSelectAll: status
            }
        });
    }

    didAllInstance = () => {
        
        this.buttonMap = {
            // 删除
            'delete':  this.action.rowAct.deleteRows,
            // 修改
            'edit': this.action.rowAct.editOnes,
            // 复制
            'copy': this.action.rowAct.copyOnes,
            // 附件管理
            'file_manager': this.fileManager,
            // 查看审批详情
            'approveinfo': this.action.rowAct.previewApproveInfo,
            'row_delete':  this.action.rowAct.deleteRows,
            // 修改
            'row_edit': this.action.rowAct.editOnes,
            // 复制
            'row_copy': this.action.rowAct.copyOnes,
            // 附件管理
            'row_file_manager': this.fileManager,
            // 查看审批详情
            'row_approveinfo': this.action.rowAct.previewApproveInfo
        };
    }

    // 行上的附件管理
    fileManager = (...args) => {
        this.pubSub.publish('fileManager', ...args);
    }

    // 行上的操作按钮点击
    rowClickHandle = (key, record, index) => {
        let selectedRows = [record];

        console.log(key, record);

        this.buttonMap[key](selectedRows);
    }

    // 主页面主表格行双击事件
    doubleClick = (record, index, fProps, e) => {
        const {action} = this.comp;

        action.formAct.toBrowsePage([record]);
    }
}